from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJWSSerializer, BadData


def generate_save_user_token(openid):
    """对openid加密"""
    # 创建一个加密的序列化对象
    serializer = TJWSSerializer(settings.SECRET_KEY, 600)
    # 调用dumps(JSON字典)方法进行加密
    token = serializer.dumps({'openid': openid}).decode()
    # 把加密后的openid返回
    return token


def check_save_user_token(openid):
    """传入加密的openid进行解密并返回"""
    # 创建一个加密的序列化对象
    serializer = TJWSSerializer(settings.SECRET_KEY, 600)

    # 调用loads进行解密
    try:
        data = serializer.loads(openid)
    except BadData:
        return
    else:
        return data.get('openid')
